<?php
namespace app\spadmin\controller\content;
use app\common\controller\Backend;

class Category extends Backend{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('ArticleCategory');
        $this->category = model('ArticleCategory')->where('status',1)->order('sort desc')->column('id,title,id,pid,module_type');
        $this->assign('category',formatTree(listToTree($this->category)));
    }

    public function index(){
        $this->request->filter(['strip_tags', 'trim']);
        if($this->request->isAjax()){
            $data = $this->request->param();
            if (isset($data['keywords']) && $data['keywords']) {
                $map['title'] = ['like', '%' . $data['keywords'] . '%'];
            }
            if (isset($data['module_type']) && $data['module_type']) {
                $map['module_type'] = $data['module_type'];
            }
            if (isset($data['status']) && $data['status']) {
                $map['status'] = $data['status'];
            } else {
                $map['status'] = 1;
            }
            $list =   $this->model->where($map)->order('sort desc')->paginate($data['limit'])->toArray();
            
            foreach ($list['data'] as $key => &$value) {
                $value['parent_name'] = $value['pid']? $this->category[$value['pid']]['title']:'顶级分类';
                $value['module_name'] = $value['module_type']=='page'?'单页':'列表';
            }
        
            
            return $this->result($list);
        }
        return $this->view->fetch();
    }
    public function edit($ids=null){
        $row = $this->model->get($ids);
        if($this->request->isPost()){
            if($row == null){
                $row = $this->model;
            }
            $data = $this->request->post('',[],'strip_tags');
            $data['content'] = $this->request->post('content','');
            $result = $row->validate()->allowField(true)->save($data,$data['id']?['id'=>$data['id']]:null);
            if($result === false){
                $this->error($row->getError());
            }
            $this->success('操作成功');
        }
        $this->assign('info',$row);
        return $this->view->fetch();

    }

}